package com.jzqf.bluetooth.client

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Intent
import android.util.Log
import com.jzqf.bluetooth.Api
import com.jzqf.bluetooth.event.EventCode
import com.jzqf.bluetooth.event.EventMessage
import org.greenrobot.eventbus.EventBus
import java.io.InputStream
import java.io.OutputStream
import java.lang.reflect.Method
import java.util.concurrent.Executors

/**
 * 普通蓝牙连接方式-客户端
 */
class ClientService(val context: Activity) {
    private val executor = Executors.newCachedThreadPool()
    private val TAG = "【ClientService】"
    private var inputStream: InputStream? = null
    private var outputStream: OutputStream? = null
    private var bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
    private var bluetoothSocket: BluetoothSocket? = null
    private val REQUEST_CODE_BLUE = 1003

    fun connect() {
        if (bluetoothAdapter == null || !bluetoothAdapter!!.isEnabled) {
            val intentBlue = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            context.startActivityForResult(intentBlue, REQUEST_CODE_BLUE)
            Log.d(TAG, "bluetoothAdapter is disenable")
            return
        }
        bluetoothAdapter!!.cancelDiscovery()
        val bluetoothDevice = bluetoothAdapter!!.getRemoteDevice(Api.address)
        when (bluetoothDevice.bondState) {
            BluetoothDevice.BOND_NONE -> {
                //蓝牙未绑定
//                val createBond = bluetoothDevice.createBond()
//                Log.d(TAG,"蓝牙绑定:$createBond")
            }
            BluetoothDevice.BOND_BONDED -> {

            }
            BluetoothDevice.BOND_BONDING -> {

            }
        }
        try {
            bluetoothSocket =
                bluetoothDevice.createInsecureRfcommSocketToServiceRecord(Api.SPP_UUID)
        } catch (e: Exception) {
            e.printStackTrace()
            //        bluetoothSocket = bluetoothDevice!!.javaClass.getMethod(
//            "createRfcommSocket", *arrayOf<Class<*>?>(
//                Int::class.javaPrimitiveType
//            )
//        ).invoke(bluetoothDevice, 1) as BluetoothSocket?
            try {
                val method: Method =
                    bluetoothDevice.javaClass.getMethod("createRfcommSocket", Integer.TYPE)
                bluetoothSocket = method.invoke(bluetoothDevice, 1) as BluetoothSocket?
                socketConnect()
            } catch (e: Exception) {
                e.printStackTrace()
                bluetoothSocket?.close()
            }
        }

        bluetoothSocket?.let {
            socketConnect()
        }
        Log.d(TAG, "蓝牙连接 Thread=${Thread.currentThread().name}")

    }

    private fun socketConnect() {
        if (bluetoothSocket == null) {
            Log.d(TAG, "bluetoothSocket is null")
            return
        }
        executor.submit {
            try {
                Log.i(
                    TAG,
                    "连接1:${bluetoothSocket!!.isConnected} Thread =${Thread.currentThread().name}"
                )
                if (!bluetoothSocket!!.isConnected) {
                    //在调用 connect() 时，应始终确保设备未在执行设备发现。 如果正在进行发现操作，
                    // 则会大幅降低连接尝试的速度，并增加连接失败的可能性。
                    // connect必须新开线程创建连接
                    bluetoothSocket!!.connect()
                }
                EventBus.getDefault().post(
                    EventMessage(
                        EventCode.RESULT,
                        "连接:${bluetoothSocket!!.isConnected} Thread =${Thread.currentThread().name}"
                    )
                )
                inputStream = bluetoothSocket!!.inputStream
                outputStream = bluetoothSocket!!.outputStream
                //这个去掉下次就连不上了
                while (true) {
                    read()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun read() {
        inputStream?.let {
            val byteArray = ByteArray(it.available())
            if (byteArray.isNotEmpty()) {
                it.read(byteArray)
                val value = String(byteArray)
                EventBus.getDefault()
                    .post(EventMessage(EventCode.RESULT, value))
            }
        }

    }

    fun writeData(string: String) {
        writeData(string.toByteArray())
    }

    fun writeData(byteArray: ByteArray) {
        if (!checkConnect()) {
            return
        }
        outputStream?.write(byteArray)
        outputStream?.flush()
    }

    private fun checkConnect(): Boolean {
        if (bluetoothSocket == null) {
            EventBus.getDefault()
                .post(EventMessage(EventCode.RESULT, "蓝牙已断开连接，别TM发数据了"))
            return false
        }
        return bluetoothSocket!!.isConnected
    }

    fun close() {
        inputStream?.close()
        outputStream?.close()
    }
}